package org.noobie.photopicker.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import org.noobie.photopicker.R;
import org.noobie.photopicker.common.Global;
import org.noobie.photopicker.domain.PhotoPickerDomain;
import org.noobie.photopicker.entity.Photo;
import org.noobie.photopicker.listener.OnLocalRecentListener;
import org.noobie.photopicker.util.CommonUtils;
import org.noobie.photopicker.view.PhotoViewPager;

import java.util.ArrayList;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * 大图预览界面
 */
public class PhotoPreviewFragment extends SupportFragment implements OnLocalRecentListener, ViewPager.OnPageChangeListener, View.OnClickListener {
    public static final int REQUEST_CODE = 23;
    /**
     * 图片展示
     */
    private PhotoViewPager mViewPager;
    /**
     * 中间图片张数标识
     */
    private TextView tvPercent;
    /**
     * 选中标识
     */
    private CheckBox checkBox;
    /**
     * 当前显示的所有图片列表
     */
    protected List<Photo> photos;
    /**
     * 当前选中的列表
     */
    protected ArrayList<Photo> tempSelectList;
    /**
     * 当前显示位置
     */
    protected int current;
    /**
     * viewpager是否正在滑动
     */
    boolean isScrolling;
    /**
     * 顶部标题栏是否隐藏了
     */
    protected boolean isUp;

    private Toast mToast;

    private PhotoPickerDomain photoSelectorDomain;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.activity_photopreview, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvPercent = view.findViewById(R.id.tv_title);
        mViewPager = view.findViewById(R.id.vp_base_app);
        checkBox = view.findViewById(R.id.cb_preview_choice);

        view.findViewById(R.id.cb_preview_choice_layout).setOnClickListener(this); // 右上角的点击区域
        view.findViewById(R.id.btn_back_app).setOnClickListener(this); // 返回按钮
        mViewPager.addOnPageChangeListener(this);

        mToast = Toast.makeText(getContext(), "", Toast.LENGTH_SHORT);

        photoSelectorDomain = new PhotoPickerDomain(getContext().getApplicationContext());

        tempSelectList = new ArrayList<>();
        init(getArguments());
    }

    protected void init(Bundle extras) {
        if (extras == null)
            return;

        if (extras.containsKey("photos")) {
            // 预览选中的图片
            photos = extras.getParcelableArrayList("photos");
            tempSelectList.addAll(photos);
            current = extras.getInt("position", 0);
            updatePercent();
            bindData();
        } else if (extras.containsKey("album")) {
            // 查看文件目录下的全部照片// 相册
            String albumName = extras.getString("album");
            tempSelectList = extras.getParcelableArrayList("selected");
            this.current = extras.getInt("position");
            if (!CommonUtils.isNull(albumName) && albumName.equals(PhotoPickerFragment.RECENT_PHOTO)) {
                photoSelectorDomain.getRecent(this);
            } else {
                photoSelectorDomain.getAlbum(albumName, this);
            }
        }
        if (tempSelectList == null) {

        }
    }

    @Override
    public void onPhotoLoaded(List<Photo> photos) {
        this.photos = photos;
        updatePercent();
        bindData(); // 更新界面
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mViewPager.removeOnPageChangeListener(this);
    }

    /**
     * 绑定数据，更新界面
     */
    protected void bindData() {
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(current);
    }

    private PagerAdapter mPagerAdapter = new PagerAdapter() {

        @Override
        public int getCount() {
            return photos == null ? 0 : photos.size();
        }

        @NonNull
        @Override
        public View instantiateItem(final ViewGroup container, final int position) {
            PhotoPreview photoPreview = new PhotoPreview(container.getContext());
            container.addView(photoPreview);
            photoPreview.loadImage(photos.get(position));
            photoPreview.setOnClickListener(photoItemClickListener);
            return photoPreview;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

    };

    @Override
    public void onClick(View v) {
        if (isUp || isScrolling) {
            //正在滑动时不允许点击
            return;
        }
        if (v.getId() == R.id.btn_back_app) {
            finish();
        } else if (v.getId() == R.id.cb_preview_choice_layout) {
            clickCheckBox();
        }
//            if (checkBox.isChecked()) {
//                checkBox.setChecked(false);
//            } else {
//                checkBox.setChecked(true);
//            }
//        }
    }

    public void finish() {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(Global.Def.KEY_SELECT, tempSelectList);
        setFragmentResult(RESULT_OK, bundle);
        pop();
    }

    /**
     * checkBox的点击事件
     */
    private void clickCheckBox() {
        if (checkBox.isChecked()) {
            //取消当前的选中
            checkBox.setChecked(false);
            tempSelectList.remove(photos.get(current));
        } else {
            if (tempSelectList.size() < Global.Ref.MAX_IMAGE) {
                //新增选中
                checkBox.setChecked(true);
                tempSelectList.add(photos.get(current));
            } else {
                checkBox.setChecked(false);
                mToast.setText(getString(R.string.max_img_limit_reached, Global.Ref.MAX_IMAGE));
                mToast.show();
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        isScrolling = arg0 == 1;
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int arg0) {
        current = arg0;
        updatePercent();
    }

    protected void updatePercent() {
        tvPercent.setText((current + 1) + "/" + photos.size());
        //该张图是否被选中(gridview有缓存左右，因此要根据当前显示的图片判断)
        checkBox.setChecked(tempSelectList.contains(photos.get(current)));
    }

    /**
     * 图片点击事件回调
     */
    private View.OnClickListener photoItemClickListener = v -> {
        finish();
//        if (!isUp) {
//            new AnimationUtil(getApplicationContext(), R.anim.translate_up)
//                    .setInterpolator(new LinearInterpolator()).setFillAfter(true).startAnimation(layoutTop);
//            isUp = true;
//            checkBox.setEnabled(false);
//            checkLayout.setEnabled(false);
//        } else {
//            new AnimationUtil(getApplicationContext(), R.anim.translate_down_current)
//                    .setInterpolator(new LinearInterpolator()).setFillAfter(true).startAnimation(layoutTop);
//            isUp = false;
//            checkBox.setEnabled(true);
//            checkLayout.setEnabled(true);
//        }
    };
}
